﻿using CSharpTest.Dameng;
using Dm;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data;

public partial class Program
{
    internal static void DmDataSelect(IServiceProvider serviceProvider)
    {
        var config = serviceProvider.GetRequiredService<IConfiguration>();

        using var conn = new DmConnection(config.GetConnectionString("DamengDb") ?? "");
        conn.Open();
        var cmdText = "select * from \"app_user\"";
        var cmd = new DmCommand(cmdText, conn);
        using var reader = cmd.ExecuteReader();
        var list = new List<User>();
        while (reader.Read())
        {
            list.Add(new User
            {
                Id = reader.GetInt32(0),
                Name = reader.GetString(1),
                Gender = reader.GetString(2),
                Birthday = reader.GetDateTime(3),
            });
        }
        var logger = serviceProvider.GetRequiredService<ILogger<Program>>();
        logger.LogInformation("User表数据：{@list}", list);
    }
    internal static async Task DmDataEfSelect(IServiceProvider serviceProvider)
    {
        var db = serviceProvider.GetRequiredService<DmDbContext>();
        await db.Database.MigrateAsync();
        if (!db.Schools.Any())
        {
            var school = new CSharpTest.Dameng.School { Name = "山西警专", Address = "旧晋祠路" };
            await db.Schools.AddAsync(school);
            if (!db.Users.Any())
            {
                await db.Users.AddAsync(new User { Name = "张三", Gender = "男", Birthday = DateTime.Parse("1981-3-9"), School = school });
            }
        }
        await db.SaveChangesAsync();


        var list = db.Users.ToList();
        var logger = serviceProvider.GetRequiredService<ILogger<Program>>();
        logger.LogInformation("EF查User表数据：{@list}", list);

        var schools = db.Schools.ToList();
        logger.LogInformation("EF查School表数据：{@schools}", schools);
    }

}
namespace CSharpTest
{
    public static class SerilogServiceCollectionExtensions
    {
        public static void RegisterDameng(this IServiceCollection services)
        {
            services.AddDbContext<DmDbContext>((serviceProvider, options) =>
            {
                var config = serviceProvider.GetRequiredService<IConfiguration>();
                options.UseDm(config.GetConnectionString("DamengDb") ?? "");
            });
        }
    }
}
namespace CSharpTest.Dameng
{
    class DmDbContext(DbContextOptions<DmDbContext> options) : DbContext(options)
    {
        public DbSet<User> Users { get; set; }
        public DbSet<School> Schools { get; set; }
    }
    [Table("app_user")]
    class User
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        [Column("id")]
        public int Id { get; set; }
        [Column("name")]
        public required string Name { get; set; }
        [Column("gender")]
        public required string Gender { get; set; }
        [Column("birthday")]
        public DateTime Birthday { get; set; }
        [Column("school_id")]
        [ForeignKey(nameof(School))]
        public int SchoolId { get; set; }
        public School? School { get; set; }
    }
    [Table("app_school")]
    class School
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        [Column("id")]
        public int Id { get; set; }
        [Column("name")]
        public required string Name { get; set; }
        [Column("address")]
        public required string Address { get; set; }
        public List<User> Users { get; set; } = [];
    }
    //参考https://learn.microsoft.com/zh-cn/ef/core/cli/dbcontext-creation?tabs=dotnet-core-cli
    class DmDbContextFactory : IDesignTimeDbContextFactory<DmDbContext>
    {
        public DmDbContext CreateDbContext(string[] args)
        {
            var config = new ConfigurationBuilder()
                 .AddJsonFile("appsettings.json").Build();

            var builder = new DbContextOptionsBuilder<DmDbContext>();
            builder.UseDm(config.GetConnectionString("DamengDb") ?? "");
            return new DmDbContext(builder.Options);
        }
    }
}